import { baseUrl } from '@/sheep/config';
import sheep from '@/sheep';

const upload = (filePath, successCallback) => {
  console.log(filePath);
  uni.uploadFile({
    url: `${baseUrl}/api/common/uploadFile`,
    filePath,
    fileType: 'image',
    name: 'pics',
    formData: {
      'file': 'pics',
    },
    header: {
      // #ifdef MP
      'Content-Type': 'multipart/form-data',
      // #endif
      ['token']: uni.getStorageSync('token'),
      'file': filePath,
    },
    success: async (info) => {
      successCallback(JSON.parse(info.data).data);
    },
  });
};

const uploadFile = (filePath, tempFilesSize, successCallback) => {
  uni.getImageInfo({
    src: filePath,
    success: async (ress) => {
      // uni.showLoading({
      //   title: '图片上传中',
      // });
      // 代表base64
      if (tempFilesSize == -1) {
        const { data } = await sheep.$api.user.uploadBse64({
          base64: ress.path.split(',')[1],
          base: 'png',
        });
        successCallback(data.data);
        return;
      }
      if (!!tempFilesSize && tempFilesSize <= 2097152) {
        const info = await upload(ress.path, successCallback);
        return;
      }
      // uploadImg(canvasPath.tempFilePath)
      let canvasWidth, canvasHeight, xs, maxWidth = 750;
      xs = ress.width / ress.height; // 宽高比例
      if (ress.width > maxWidth) {
        canvasWidth = maxWidth; // 这里是最大限制宽度
        canvasHeight = maxWidth / xs;
      } else {
        canvasWidth = ress.width;
        canvasHeight = ress.height;
      }
      let canvas = uni.createCanvasContext('canvas');
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;
      canvas.clearRect(0, 0, canvasWidth, canvasHeight);
      canvas.drawImage(ress.path, 0, 0, canvasWidth, canvasHeight);
      canvas.save();
      // 这里的画布drawImage是一种异步属性  可能存在未绘制全就执行了draw的问题  so添加延迟
      setTimeout(e => {
        canvas.draw(true, () => {
          uni.canvasToTempFilePath({
            canvasId: 'canvas',
            fileType: 'JPEG',
            destWidth: canvasWidth,
            destHeight: canvasHeight,
            quality: 0.7,
            success: function(canvasPath) {
              console.log(canvasPath);
              upload(canvasPath.tempFilePath, successCallback);
            },
          });
        });
      }, 200);
    },
  });
};

export default {
  upload,
  uploadFile,
};